import { Application, useApplicationRepository } from '@/store/application-repository';
import { IPage } from './types';
import { guid, traverseTree } from '@/util';
import { RouteRecordNameGeneric } from 'vue-router';
import { APPLICATION_DETAIL_ROUTE } from '@/router';

export function useApplicationService() {
  const applicationRepository = useApplicationRepository();

  // 获取系统中的应用
  const applications = (systemId: string): Promise<IPage<Application>> => {
    return new Promise(resolve => {
      resolve({ current: 1, size: 10, records: applicationRepository.getApplications(systemId) });
    });
  };

  const getApplication = (applicationId: string): Promise<Application | undefined> => {
    const application_ = applicationRepository.getApplication(applicationId);
    return new Promise(resolve => {
      resolve(application_);
    });
  };

  const addOrEditApplication = (application: Application): Promise<Application> => {
    let application_ = application;
    if (application.id) {
      // TODO 编辑
    } else {
      application_ = { ...application, id: guid() };
      applicationRepository.addApplication(application_);
    }
    return new Promise(resolve => {
      resolve(application_);
    });
  };

  const applicationDetailPages = computed(() => {
    const projectDetailPages_ = new Set();
    traverseTree(
      node => {
        projectDetailPages_.add(node.name);
      },
      [APPLICATION_DETAIL_ROUTE],
    );
    return projectDetailPages_;
  });

  const getIsApplicationDetail = (routeName: RouteRecordNameGeneric): boolean => {
    return applicationDetailPages.value.has(routeName as string);
  };

  return { applications, getApplication, addOrEditApplication, getIsApplicationDetail };
}
